package cn.huiyunche.base.service.framework.utils;

import cn.huiyunche.base.service.constant.HJBConstant;
import cn.huiyunche.base.service.constant.WeixinConstant;
import cn.huiyunche.base.service.model.SHjbOrderLog;
import cn.huiyunche.base.service.vo.HJBOrderFormVo;
import cn.huiyunche.tools.basic.exceptions.BusinessException;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * 网络工具类
 *
 * @author hdy [Tuffy]
 */
public class HttpUtils {

    private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * 返回数据编码格式
     */
    public static final String encoding_utf8 = "UTF-8";
    public static final String encoding_gbk = "GBK";

    /**
     * 获取请求
     *
     * @return request
     */
    public static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    /**
     * 获取response
     *
     * @return response
     */
    public static HttpServletResponse getResponse() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    }

    /**
     * 获取session
     *
     * @return session
     */
    public static HttpSession getSession() {
        return getRequest().getSession();
    }


    /**
     * 获取主机地址 + 跟路径
     *
     * @return 地址信息
     */
    public static String getHostAddressWithContextPath() {
        String rtnAddress = "";
        HttpServletRequest hsr = HttpUtils.getRequest();
        String host = HYCUtils.getConstantPropertiesLoader().getProperty(WeixinConstant.HOST_ADDRESS);
        rtnAddress = hsr.getScheme() + "://" + host + hsr.getContextPath();
        return rtnAddress;
    }

    /**
     * get 请求
     *
     * @param address 地址url
     * @return 请求结果
     * @throws IOException
     * @throws MalformedURLException
     */
    public static JSONObject get(String address) throws IOException {
        if (StringUtils.isBlank(address)) {
            return null;
        }
        String resultString = IOUtils.toString(new URL(address));
        if (StringUtils.isBlank(resultString)) {
            return null;
        }
        return JSONObject.parseObject(resultString);
    }

    /**
     * 微信post请求
     *
     * @param strURL   url
     * @param jsonData 数据
     * @return 结果集
     */
    public static JSONObject weixinPost(String strURL, String jsonData) {
        String result = null;
        try {
            URL url = new URL(strURL); // 创建连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST"); // 设置 POST 请求方式
            OutputStream out = conn.getOutputStream();
            out.write(jsonData.getBytes(HttpUtils.encoding_utf8));
            out.flush();
            out.close();
            // 读取响应
            BufferedReader buf = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            result = buf.readLine();
            return JSONObject.parseObject(result);
        } catch (IOException e) {
            logger.error("http请求异常(IOException) ： {}", e);
            throw new BusinessException("http请求异常!");
        }
    }

    /**
     * 汇聚保 下单接口
     *
     * @param horv
     * @return
     * @throws IOException
     * @throws ClientProtocolException
     */
    public static SHjbOrderLog hjbOrderPost(HJBOrderFormVo horv) throws IOException {
        String url = HYCUtils.getConstantPropertiesLoader().getProperty(HJBConstant.HJB_REQUEST_URL);
        HttpPost request = new HttpPost(url);
        //转换为NameValuePair
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // 汇聚保建议 运单号填写  待定
        horv.getExtrainfo().setFreightNo("待定");
        params.add(new BasicNameValuePair("channelId", horv.getChannelId()));
        params.add(new BasicNameValuePair("channelOrderNo", horv.getChannelOrderNo()));
        params.add(new BasicNameValuePair("notifyUrl", horv.getNotifyUrl()));
        params.add(new BasicNameValuePair("productCode", horv.getProductCode()));
        params.add(new BasicNameValuePair("extraInfo", JSONObject.toJSONString(horv.getExtrainfo())));
        request.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
        // 使用http调用请求
        HttpClient client = new DefaultHttpClient();
        HttpResponse response = client.execute(request);
        HttpEntity responseEntity = response.getEntity();
        InputStream inputStream = responseEntity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        String str = sb.toString();
        if (str.startsWith("<html>")) {
            SHjbOrderLog sol = new SHjbOrderLog();
            sol.setIsSuccess("N");
            sol.setChannelOrderNo(horv.getChannelOrderNo());
            sol.setErrMsg("请求汇聚保服务器异常");
            return sol;
        }
        return JSONObject.parseObject(sb.toString(), SHjbOrderLog.class);
    }

    /**
     * 获取浏览器段ip
     *
     * @return ip
     */
    public static String getUserIp() {
        String ip = getRequest().getHeader("x-forwarded-for");
        logger.info("get IP from x-forwarded-for：{}", ip);
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = getRequest().getHeader("Proxy-Client-IP");
            logger.info("get IP from Proxy-Client-IP：{}", ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = getRequest().getHeader("WL-Proxy-Client-IP");
            logger.info("get IP from WL-Proxy-Client-IP：{}", ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = getRequest().getHeader("HTTP_CLIENT_IP");
            logger.info("get IP from HTTP_CLIENT_IP：{}", ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = getRequest().getHeader("HTTP_X_FORWARDED_FOR");
            logger.info("get User IP from HTTP_X_FORWARDED_FOR： {}", ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = getRequest().getRemoteAddr();
            logger.info("get User IP {}：", ip);
        }
        if (ip != null && ip.contains(",")) {
            ip = ip.substring(0, ip.indexOf(","));
            logger.info("get User IP after substring  :{}", ip);
        }
        return ip;
    }
}
